/**
 * Created by godhh on 16/9/9.
 */

import $ from 'jquery'
import angular from 'angular'
import util from '@yunke/core/util'
import ui from '@yunke/core/ui'
import _ from 'lodash'
import 'apiService'
import 'angular-ui'
import 'angular-messages'

import setBudgetTpl from '../dialog/set_budget.html'
import '../css/budget.less'

angular.module('Budget', ['ngPublicUI', 'ngMessages', 'ApiService'])
    .config((apiProvider) => {

        const api = apiProvider.$get();

        api.setApis({
            ls: {
                url: '/api/index.php?r=budget/list'
            },
            bsave: {
                url: '/api/index.php?r=budget/save',
                method: 'post'
            }
        });

        api.setUseFormData(false);

    })
    .controller('budgetCtl', ['$rootScope', '$scope', '$q', '$timeout', 'api', ($rootScope, $scope, $q, $timeout, api) => {

        const service = api.getService();

        const keys = _.range(1, 13).concat('total');

        $scope.Page = {
            setBudgetTpl,
            canSet: (item) => item.year == new Date().getFullYear(),
            items: [],
            ls: () => {
                service.ls()
                    .then((res) => {
                        _.each(res.data.data, item => {
                            _.each(item.detail || [], x => {
                                _.each(keys, k => x[k] = +x[k] / 10000);
                            })
                        });
                        $scope.Page.items = res.data.data;
                    })
            },
            reset: () => $scope.Page.ls(),
            setBudgetBeforeShow: ($dialog, $dialogScope, item, canSet) => {
                const $data = $dialogScope.data;
                angular.extend($data, item, {canSet});
                $dialogScope.keyup = (v) => +(v.replace(/[^\d]/g, ''))
            },
            setBudget: ($data) => {
                if ($data.canSet) {
                    let data = _.cloneDeep($data);
                    _.each(data.detail, x => {
                        _.each(keys, k => x[k] = +x[k] * 10000);
                    });
                    service.bsave(_.merge(data, {USE_FORM_DATA: true}))
                        .then(() => ui.showSucTip('设置成功'))
                        .then(() => $scope.Page.ls());
                }
            },
            init: () => {

                $scope.Page.reset(1);

            }
        };

        /**
         * 初始化
         */
        $scope.Page.init();

    }]);
